//
//  ShoppingCartView.m
//  MeiTuanWaiMai
//
//  Created by maxin on 16/1/5.
//  Copyright © 2016年 maxin. All rights reserved.
//

#import "ShoppingCartView.h"
#import "BadgeView.h"
#import "RestaurantViewModel.h"

@implementation ShoppingCartView
{
    int M;
    NSString *amount;
    NSInteger money;
}
-(instancetype) initWithFrame:(CGRect)frame inView:(UIView *)parentView
{
    self = [super initWithFrame:frame];
    if (self) {
        self.parentView = parentView;
        [self layoutUI];
    }
    return self;
}

-(void)layoutUI{

    M=0;
    self.minFreeMoney = 20;
    
    self.line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
    self.line.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.line.layer.borderWidth = 0.25;
    [self addSubview:self.line];
    
    //购物金额提示框
    self.money = [[UILabel alloc] initWithFrame:CGRectMake(70, 10, self.bounds.size.width-140, 30)];
    [self.money setTextColor:[UIColor grayColor]];
    [self.money setText:@"未选购商品"];
    [self.money setFont:[UIFont systemFontOfSize:13.0]];
    [self addSubview:self.money];
    
    
    //结账按钮
    self.payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.payButton.frame = CGRectMake(SCREEN_WIDTH - 100, 5, 90,35);
    [self.payButton addTarget:self action:@selector(payclick:) forControlEvents:UIControlEventTouchUpInside];
    self.payButton.layer.cornerRadius = 5;
    self.payButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    self.payButton.backgroundColor = [UIColor lightGrayColor];
    [self.payButton setTitle:[NSString stringWithFormat:@"请选购"] forState:UIControlStateNormal];
    self.payButton.enabled = NO;
    [self addSubview:self.payButton];
    
    
    //购物车
    self.shoppingCartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shoppingCartBtn setUserInteractionEnabled:NO];
    [self.shoppingCartBtn setBackgroundImage:[UIImage imageNamed:@"购物车"] forState:UIControlStateNormal];
    self.shoppingCartBtn.frame = CGRectMake(10, -10, 50,50);
    [self.shoppingCartBtn addTarget:self action:@selector(shoppCartClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.shoppingCartBtn];
    
    //小圆点
    self.badge = [[BadgeView alloc] initWithFrame:CGRectMake(self.shoppingCartBtn.frame.size.width - 18, 5, 18, 18) withString:nil];
    [self.shoppingCartBtn addSubview:self.badge];
     self.badge.hidden = YES;
    
    int maxHeight = self.parentView.frame.size.height - 250;
    self.OrderList = [[GoodsListView alloc] initWithFrame:CGRectMake(0,self.parentView.frame.size.height - maxHeight, SCREEN_WIDTH, maxHeight) withObjects:nil  canReorder:YES];
    
    self.OverlayView = [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-50)];
    self.OverlayView.ShoppingCartView = self;
    [self.OverlayView addSubview:self];
    [self.parentView addSubview:self.OverlayView];
    self.OverlayView.alpha = 0.0;
    self.open = NO;
}


-(void)setBadgeValue:(NSInteger)badgeValue{

    _badgeValue = badgeValue;
    self.badge.textLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)badgeValue];
    if (badgeValue>0) {
        self.badge.hidden = NO;
    }
    else{
        self.badge.hidden = YES;
    }
   
}


#pragma mark 结算
- (void)payclick:(id)sender {

    
    money = [[NSUD objectForKey:@"money"] integerValue] - amount.integerValue;

    NSLog(@"%ld",money);
    
    M++;
    if (M==1) {
        [self.payButton setTitle:@"提交订单" forState:UIControlStateNormal];

        [self updateFrame:self.OrderList];
        [self.OverlayView addSubview:self.OrderList];
        
        [UIView animateWithDuration:0.5 animations:^{
            CGPoint point = self.shoppingCartBtn.center;
            CGPoint labelPoint = self.money.center;
            
            point.y -= (self.OrderList.bounds.size.height + 50);
            labelPoint.x -= 60;
            self.OverlayView.alpha = 1.0;
            
            [self.shoppingCartBtn setCenter:point];
            [self.money setCenter:labelPoint];
        } completion:^(BOOL finished) {
            
            self.open = YES;
        }];

    }else if (M==2){
        
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        
        if (money >=0) {
            NSLog(@"提交订单%@", self.OrderList.objects);
            
            NSMutableArray *orderarr = [[NSMutableArray alloc]init];
            NSString *string  = [[NSString alloc]init];
            for (NSMutableDictionary  *dict in self.OrderList.objects) {
                
                [dict removeObjectForKey:@"praise_content"];
                [dict removeObjectForKey:@"month_saled"];
                [dict removeObjectForKey:@"price"];
                [dict removeObjectForKey:@"amount"];
                [dict removeObjectForKey:@"isLoading"];
                
                string = [NSString stringWithFormat:@"%@-%@",dict[@"id"],dict[@"orderCount"]];
                [orderarr addObject:string];
                
            }
            
        
            NSString *scheduledId = [orderarr componentsJoinedByString:@","];
            NSDictionary *dict =@{@"totalPrice":amount,@"token":[NSUD objectForKey:@"token"],@"arr":scheduledId,@"payment":@"ONECARD",@"phone":[NSUD objectForKey:@"MDC_userCode"],@"reStatus":@"0"};
            
            [RestaurantViewModel requestWithUrlForRestaurantSubmit:self andParam:dict success:^(NSMutableArray *model) {
                
                
                [self setBadgeValue:0];
                [self.OrderList.objects removeAllObjects];
                [self.OrderList.tableView reloadData];
                [self dismissAnimated:YES];
                [self setTotalMoney:0];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteDate" object:self userInfo:nil];
                
                UIWindow * window = [UIApplication sharedApplication].keyWindow;
                
                [NSUD setObject:[NSString stringWithFormat:@"%ld",money] forKey:@"money"];//保存余额

                [MBProgressHUD showSuccess:@"订单提交成功" toView:window];
                
                M=0;
                
            } failure:^(NSString *error) {
                
                
                [MBProgressHUD showError:error toView:window];
                
                M=1;
                
            }];
            
        }else{

            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:@"账户积分不足支付该订单，请到前台进行充值！"toView:window];
            M=1;

        }
    
        
        
        
        
        
        
    }
}

#pragma  mark 点击购物车
- (void)shoppCartClick:(id)sender {
    if (!self.badgeValue>0) {
        [self.shoppingCartBtn setUserInteractionEnabled:NO];
        return;
    }
    
    [self.payButton setTitle:@"提交订单" forState:UIControlStateNormal];

    M++;
    [self updateFrame:self.OrderList];
    [self.OverlayView addSubview:self.OrderList];
    
    [UIView animateWithDuration:0.5 animations:^{
        CGPoint point = self.shoppingCartBtn.center;
        CGPoint labelPoint = self.money.center;
        
        point.y -= (self.OrderList.frame.size.height + 50);
        labelPoint.x -= 60;
        self.OverlayView.alpha = 1.0;
        
        [self.shoppingCartBtn setCenter:point];
        [self.money setCenter:labelPoint];
    } completion:^(BOOL finished) {
        
        self.open = YES;
    }];

}


#pragma  mark 更新ListView 的高度
-(void)updateFrame:(GoodsListView *)orderListView
{
    if(orderListView.objects.count ==0){
        [self dismissAnimated:YES];
        return;
    }
    float height = 0;
    height = [orderListView.objects count] * 50;
    int maxHeight = self.parentView.frame.size.height - 250;
    if (height >= maxHeight) {
        height = maxHeight;
    }

    float orignY = self.OrderList.frame.origin.y;
    
    self.OrderList.frame = CGRectMake(self.OrderList.frame.origin.x, self.parentView.bounds.size.height - height - 50, self.OrderList.frame.size.width, height);
    float currentY = self.OrderList.frame.origin.y;

    if (self.open) {
        [UIView animateWithDuration:0.5 animations:^{
            CGPoint point = self.shoppingCartBtn.center;
            point.y -= orignY - currentY;
            [self.shoppingCartBtn setCenter:point];
            
        } completion:^(BOOL finished) {
            
            
        }];
    }
   
}

#pragma mark - dismiss
-(void)dismissAnimated:(BOOL)animated
{
    
    M=0;
    [self.payButton setTitle:@"查看订单" forState:UIControlStateNormal];

    
    [self.shoppingCartBtn bringSubviewToFront:self.OverlayView];
    [UIView animateWithDuration:0.5 animations:^{
        _OverlayView.alpha = 0.0;
        self.shoppingCartBtn.frame = CGRectMake(10, -10, 50,50);
        self.money.frame = CGRectMake(70, 10, self.bounds.size.width, 30);
        
    } completion:^(BOOL finished) {
        self.open = NO;
    }];
}


#pragma  mark - 计算价格
-(void)setTotalMoney:(NSInteger)nTotal
{
    self.nTotal = nTotal;
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    
    formatter.numberStyle = kCFNumberFormatterNoStyle;
    
    amount = [formatter stringFromNumber:[NSNumber numberWithInteger:nTotal]];
    
    if(self.nTotal > 0)
    {
        self.money.font = [UIFont systemFontOfSize:20.0f];
        self.money.textColor = [UIColor redColor];
        self.money.text = [NSString stringWithFormat:@"共￥%@",amount];
        NSLog(@"价格 ====== %@",amount);
//        NSInteger value = self.minFreeMoney - self.nTotal;

        if (self.nTotal > 0) {
//
            self.payButton.enabled = YES;
            if(M==0){
            [self.payButton setTitle:@"查看订单"
                            forState:UIControlStateNormal];
            }
            [self.payButton setBackgroundColor:[UIColor redColor]];
            [self.shoppingCartBtn setUserInteractionEnabled:YES];

//            self.payButton.enabled = NO;
//            [self.payButton setTitle:[NSString stringWithFormat:@"还差￥%ld",(long)value] forState:UIControlStateNormal];
//            [self.payButton setBackgroundColor:[UIColor grayColor]];
//        }
//        else
//        {
        
        }
    }else{
        [self.money setTextColor:[UIColor grayColor]];
        [self.money setText:@"未选购商品"];
        [self.money setFont:[UIFont systemFontOfSize:13.0]];
        
        self.payButton.enabled = NO;
        [self.payButton setTitle:[NSString stringWithFormat:@"请选购"] forState:UIControlStateNormal];
        [self.payButton setBackgroundColor:[UIColor grayColor]];
        
        [self.shoppingCartBtn setUserInteractionEnabled:NO];
    }
    
}


@end
